package com.mediacloud.app.newsmodule.activity

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.chinamcloud.audioserver.APSHelper
import com.chinamcloud.audioserver.MusicEntity
import com.chinamcloud.collect.AcquisitionManager
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager.Companion.getInstance
import com.jaeger.library.StatusBarUtil
import com.lzf.easyfloat.interfaces.OnPermissionResult
import com.lzf.easyfloat.permission.PermissionUtils.checkPermission
import com.mediacloud.app.appfactory.cache.UserRecommend
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.buildUrl
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleItemReciver
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.IntegralConfig
import com.mediacloud.app.model.news.ReadDataReciver
import com.mediacloud.app.model.news.ShowSwitch
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.VideoSeekKit.addHisSeek
import com.mediacloud.app.newsmodule.activity.VideoSeekKit.clearHisSeek
import com.mediacloud.app.newsmodule.activity.VideoSeekKit.getHisSeek
import com.mediacloud.app.newsmodule.fragment.NotifyMicroEvent
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoVodDetailFragment
import com.mediacloud.app.newsmodule.model.CommentListDataReciver
import com.mediacloud.app.newsmodule.model.NewsCommentItem
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter.TimeoutCallback
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics
import com.mediacloud.app.newsmodule.utils.Addintegral
import com.mediacloud.app.newsmodule.utils.CommentListDataInvoker
import com.mediacloud.app.newsmodule.utils.DisplayCutoutManager
import com.mediacloud.app.newsmodule.utils.DomainUtil
import com.mediacloud.app.newsmodule.utils.KillMusicUtils
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker
import com.mediacloud.app.newsmodule.utils.VideoAddressGet
import com.mediacloud.app.newsmodule.utils.share.IShareWrap
import com.mediacloud.app.newsmodule.utils.share.OnScreenShotListener
import com.mediacloud.app.newsmodule.utils.share.PosterShareWrap
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.reslib.analysis.AnalysisUtils
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.ListStyle
import com.mediacloud.app.reslib.enums.TitileType
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.model.UserInfo
import com.utils.ClickUtils.delayClickable
import com.utils.DeviceUtils
import com.utils.NetUtils
import com.utils.UriTool.isFromH5OpenToReStart
import com.utils.read.AudioFloatManager.Companion.getInstance
import com.utils.read.AudioFloatManager.Companion.showPermissionAsk
import com.yoake.media.player.XPlayer
import com.yoake.media.player.utils.FrameBimapKit
import com.yoake.media.player.utils.OnPlayerActionListener
import com.yoake.media.player.utils.VirtualDanmakuKit
import com.yoake.media.player.utils.XVideoBitRate
import com.yoake.media.player.utils.XVideoItem
import com.yoake.media.player.utils.XVideoSpeed
import com.yoake.media.player.utils.cache.XPlayerPreloadManager
import com.yoake.media.player.utils.interfaces.PendingPlayerChangeListener
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import xyz.doikki.videoplayer.exo.ExoMediaPlayerFactory
import xyz.doikki.videoplayer.player.BaseVideoView.OnStateChangeListener
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.util.PlayerUtils
import java.lang.reflect.Field

class VideoNewsDetailActivity : StyleSetActivity(), OnScreenShotListener {
    var isAutoPlay = true
    var mBaiduPlayer: XPlayer? = null
    var fragment: VideoVodDetailFragment? = null
    private var launchTimeLong = 0L


    var showSwitch: ShowSwitch? = null

    //支付相关
    var broccoliLayout: LinearLayout? = null
    var vodBottomContent: View? = null

    // private TextView emptyTipsText;

    // private TextView emptyTipsText;
    private val rlayout_back: View? = null
    var mTyReportStartTime: Long = 0
    var mTyReportEndTime: Long = 0

    protected var commentListInvoker: CommentListDataInvoker? = null
    protected var mCommentListCallBack: CommentListCallBack? = null
    var startPosition = 0L
    var stopPosition = 0L
    var dragBeforePosition = 0L
    var dragAfterPosition = 0L
    var videoDuration = 0L
    private var isForwardComplate = false
    private var isCompleted = false

    override fun showTitleBar(): Boolean {
        return false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        isCommentDialog = true
        super.onCreate(savedInstanceState)
        val uriData = intent.data
        if (uriData != null) {
            isFromH5OpenToReStart = isFromH5OpenToReStart(this, uriData)
            val articleid = uriData.getQueryParameter("articleid")
            val title = uriData.getQueryParameter("title")
            val cname = uriData.getQueryParameter("cname")
            val tag = uriData.getQueryParameter("tag")
            catalogItem = CatalogItem()
            catalogItem.catname = cname
            articleItem = ArticleItem()
            try {
                articleItem.title = (title)
                articleItem.id = (java.lang.Long.valueOf(articleid))
            } catch (e: Exception) {
            }
        } else {
            catalogItem = intent.getParcelableExtra("catalog")
            articleItem = intent.getParcelableExtra("data")
            if (articleItem == null) {
                articleItem = ArticleItem.praseIntentDataToArticleItem(intent, TypeX.NEWS.VIDEO)
            }
        }
        if (articleItem != null) {
            showSwitch = articleItem.getmShowSwitch()
        }
        if (catalogItem == null) {
            catalogItem = CatalogItem()
        }
        rlayout_back = findViewById(R.id.rlayout_back)
        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        if (retryTips != null) {
            retryTips.setOnClickListener { v ->
                delayClickable(v)
                if (hasNetWork) {
                    if (currentState !== TYPE_LOADING) {
                        showStateView(TYPE_LOADING, false)
                        getVideoDetail()
                    }
                } else {
                    showNetWorDialog()
                }
            }
        }
        if (rlayout_back != null) {
            rlayout_back.setOnClickListener { v ->
                delayClickable(v)
                finish()
            }
        }
        if (loadingView != null) {
            loadingView.setOnClickListener { v ->
                delayClickable(v)
                if (hasNetWork) {
                    if (currentState !== TYPE_LOADING) {
                        showStateView(TYPE_LOADING, false)
                        getVideoDetail()
                    }
                } else {
                    showNetWorDialog()
                }
            }
        }
        vodBottomContent = Utility.findViewById(mRootView, R.id.vodBottomContent)
        broccoliLayout = Utility.findViewById(mRootView, R.id.broccoliLayout)
        val isLeftImgMode = ListStyle.TotoalStyle.LEFT_IMAGE == serverAppConfigInfo.content_list
        if (isLeftImgMode) {
            for (i in 0..2) {
                broccoliLayout?.addView(
                    LayoutInflater.from(this).inflate(R.layout.layout_broccoli21, null)
                )
            }
        } else {
            for (i in 0..2) {
                broccoliLayout?.addView(
                    LayoutInflater.from(this).inflate(R.layout.layout_broccoli22, null)
                )
            }
        }
        mBaiduPlayer = Utility.findViewById(mRootView, R.id.mBaiduPlayer)
        mBaiduPlayer?.controller?.getControllerInstance()!!.setEnableOrientation(true)
        mBaiduPlayer?.isRelease = false
        mBaiduPlayer?.prepareView?.setVisibleThumb(false)
        mBaiduPlayer?.completeView?.setVisibleThumb(false)
        val linkedHashSet =
            AppFactoryGlobalConfig.getAppServerConfigInfo(this).newsDetailConfig.linkedHashSet
        if (!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(
                NewsDetailStyleConfig.SHARE_BUTTON
            )
        ) {
            mBaiduPlayer?.titleView?.hideTitleMoreView()
            mBaiduPlayer?.errorView?.hideTitleMoreView()
        }
        if (DeviceUtils.isCus(this)) {
            mBaiduPlayer?.setPlayerFactory(ExoMediaPlayerFactory.create())
        }
        //  mBaiduPlayer.setDebug(true);
        // mBaiduPlayer.setSpecial(true);
        mBaiduPlayer?.pendingSeek = getHisSeek("" + articleItem.getId())
        if (!TextUtils.isEmpty(articleItem.logo)) {
            mBaiduPlayer?.setPoster(
                buildUrl(3, articleItem.logo),
                ContextCompat.getDrawable(this, R.drawable.cctv7_loading_img)
            )
        }
        if (DeviceUtils.isCus(this)) {
            mBaiduPlayer?.showSwitchAudioBtn()
            mBaiduPlayer?.setDanmukuSwitchViewState(true, true)
            setTestDanma() //鲜产品说放开
        } else {
            mBaiduPlayer?.hideDanMu()
        }
        //虚拟弹幕
        tvLetmeSay.text = "我来说几句"

        setPlayerView()
        if (articleItem == null) return
        fragment = VideoVodDetailFragment()
        if (isAutoPlay) KillMusicUtils.stopAPS(this)
        getVideoDetail()
        setNewsTitle()
        onPageStart()
        showPageTransition()
        //设置使用刘海屏幕区域
        DisplayCutoutManager(this).set(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES)
        if (DeviceUtils.isCus(this)) {
            getCommentData()
        }
        judgeInteval()
        AddMedalStatistics.addMedalStatistics(this) //勋章统计
        if (!NetUtils.isNetConnection(this)) {
            val articleItemReciver = ArticleItemReciver()
            articleItemReciver.articleItem = articleItem
            if (hadAdded) {
                fragment!!.articleItem = articleItem
            }
            initDetailFragment(articleItemReciver, true)
            hiddBroccoliLayout()
            setVideoContent(articleItem.video)
        }
    }

    var config: IntegralConfig? = null
    var openInteval = false //是否开启积分任务

    //    boolean openGrow = false;//是否开启成长值任务
    var timeInteval = 0 //增加积分时间（分）

//    int timeGrow = 0;//增加成长值时间（分）

    //    int timeGrow = 0;//增加成长值时间（分）
    //判断是否开启积分和无和成长任务
    private fun judgeInteval() {
        config = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig
        if (config != null) {
            if (config!!.enableList1 != null && config!!.enableList1.size != 0) {
                for (i in config!!.enableList1.indices) {
                    if (config!!.enableList1[i] == 8) {
                        openInteval = true
                        timeInteval = config!!.videoLeastDuration1
                    }
                }
            }

            /*if (config.enableList4 != null && config.enableList4.size() != 0) {
                for (int i = 0; i < config.enableList4.size(); i++) {
                    if (config.enableList4.get(i) == 8) {
                        openGrow = false;
                        timeGrow = config.videoLeastDuration4;
                    }
                }
            }*/
        }
    }


    private fun getCommentData() {
        mCommentListCallBack = CommentListCallBack()
        commentListInvoker = CommentListDataInvoker(mCommentListCallBack)
        commentListInvoker!!.getAllCommentList(
            1,
            articleItem.getId().toString() + "",
            UserInfo.getUserInfo(this).userid
        )
    }

    override fun onScreenShot() {
        if (mBaiduPlayer!!.isFullScreen) {
            mBaiduPlayer!!.controller.toggleFullScreen()
            mBaiduPlayer!!.postDelayed({
                try {
                    val bitmap = mBaiduPlayer!!.doScreenShot()
                    val iShareWrap: IShareWrap? = shareWrap.share
                    shareWrap.show(mRootView)
                    if (iShareWrap is PosterShareWrap) {
                        iShareWrap.sharScreenShot(bitmap)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }, 400)
        }
    }

    inner class CommentListCallBack :
        DataInvokeCallBack<CommentListDataReciver?> {
        override fun success(data: CommentListDataReciver?) {
            if (data?.state!!) {
                if (data.commentList != null && data.commentList.size != 0) {
                    setDanma(data.commentList)
                }
            }
        }

        override fun fault(data: Any) {}
    }

    private fun setDanma(commentList: List<NewsCommentItem>) {
        val kit = VirtualDanmakuKit(this, mBaiduPlayer!!)
        for (i in commentList.indices) {
            kit.addDanma(commentList[i].content, false)
        }
    }


    private fun setTestDanma() {
        val kit = VirtualDanmakuKit(this, mBaiduPlayer!!)
        kit.addDanma("中国，你是我的骄傲", false)
        kit.addDanma("厉害了我的国", false)
        kit.addDanma("人民的国家，伟大的民族", false)
        kit.addDanma("中国有力量，人民有信仰", false)
        kit.addDanma("很庆幸生活在一个和平伟大的年代，感谢祖国感谢党", false)
        kit.addDanma("致敬", false)
        kit.addDanma("致敬", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("致敬", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("致敬", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("祝福祖国", false)
        kit.addDanma("致敬", false)
    }


    //开启语音播报
    private fun startReadNews() {
        if (TextUtils.isEmpty(lastPlayUrl)) {
            return
        }
        getInstance().voice_read(articleItem)
        articleItem.text_audio_url = lastPlayUrl
        val musicEntity = MusicEntity(
            "" + articleItem.getTitle(),
            lastPlayUrl!!
        )
        APSHelper.play(this, "" + articleItem.getId(), musicEntity, mBaiduPlayer!!.currentPosition)
        getInstance(this).article = articleItem
        getInstance(this).catalogItem = catalogItem
        getInstance(this).show()
    }

    var shareWrap //播放器更多
            : ShareWrap? = null

    /**
     * 设置视频view
     */
    private fun setPlayerView() {
        mBaiduPlayer!!.autoPlay = isAutoPlay
        val layoutParams = mBaiduPlayer!!.layoutParams
        val num = (16.0 / 9.0).toFloat()
        layoutParams.height = (resources.displayMetrics.widthPixels / num).toInt()
        mBaiduPlayer!!.layoutParams = layoutParams
        mBaiduPlayer!!.setOnTitleMoreClickListener {
            try {
                if (mBaiduPlayer!!.isFullScreen) {
                    mBaiduPlayer!!.controller.getControllerInstance()!!.hide()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            shareWrap = ShareWrap(this@VideoNewsDetailActivity, false)
            shareWrap.setShowFunction(true)
            shareWrap.init(articleItem, CatalogItem())
            shareWrap.share!!.onScreenShotListener = this@VideoNewsDetailActivity
            shareWrap.show(mRootView)
        }
    }

    fun getArticleItem(): ArticleItem? {
        return articleItem
    }

    override fun getFitSystemWindow(): Boolean {
        return true
    }


    protected fun setNewsTitle() {
        val base = serverAppConfigInfo.getBase()
        if (base == TitileType.FRAME) {
            setFrameTypeTitle()
        } else if (base == TitileType.NAVIGATE) {
            setTitle(if (catalogItem != null) catalogItem.catname else "")
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(if (articleItem != null) articleItem.getTitle() else "")
        } else if (base == TitileType.NOTITLE) {
            setTitle("")
        }
    }


    override fun onBackPressed() {
        var value = false
        if (mBaiduPlayer != null && mBaiduPlayer!!.isFullScreen) {
            mBaiduPlayer!!.onBackPressed()
            value = true
        }
        if (shareWrap != null) {
            if (shareWrap.isShowing()) {
                shareWrap.dismiss()
                value = true
            }
        }
        if (value) return
        super.onBackPressed()
    }


    private var isGoOtherPage = false

    /**
     * pause前是暂停的 回到页面不恢复播放
     */
    var isPlayBeforePause = false

    override fun onPause() {
        isPlayBeforePause =
            mBaiduPlayer != null && mBaiduPlayer!!.playStateAtLifecycleOwnerPause == VideoView.STATE_PAUSED
        super.onPause()
        if (mBaiduPlayer != null && !isFinish) {
            isGoOtherPage = true
            saveViewHistory()
            if (commentIsOpen) {
                commentIsOpen = false
                if (mBaiduPlayer?.playStateAtLifecycleOwnerPause == VideoView.STATE_PLAYING || mBaiduPlayer?.playStateAtLifecycleOwnerPause == VideoView.STATE_PREPARING || mBaiduPlayer!!.playStateAtLifecycleOwnerPause == VideoView.STATE_PREPARED) {
                    mBaiduPlayer!!.start()
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun restorePause(event: NotifyMicroEvent) {
        //防止点击home键，评论框pause了，视频也应该pause
        if (mBaiduPlayer != null) {
            if (event.play) {
                if (!isPlayBeforePause) mBaiduPlayer!!.resume()
            } else {
                mBaiduPlayer!!.pause()
            }
        }
    }


    /**
     * 这里真实的去finish() 用于
     * 处理退出当前也没的时候，需要申请悬浮窗权限的时候，不能真实的调用finish()否则取不到权限申请的结果
     */
    fun realFinish() {
        super.finish()
        //        onVideoPlayEndEvent();
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis()
        }
        if (readStatusInvoker != null) readStatusInvoker!!.destory()
        readStatusInvoker = null
        if (mBaiduPlayer != null) {
            saveViewHistory()
        }
        try {
            if (fragment != null) {
                val transaction = supportFragmentManager.beginTransaction()
                transaction.remove(fragment!!)
                transaction.commitNowAllowingStateLoss()
            }
        } catch (ex: Exception) {
        }
        if (mBaiduPlayer != null) {
            val frameBimapKit = mBaiduPlayer!!.frameBimapKit
            if (frameBimapKit != null) {
                frameBimapKit.cancelTask()
                lifecycle.removeObserver(frameBimapKit)
                var contextField: Field? = null
                try {
                    contextField = FrameBimapKit::class.java.getDeclaredField("context")
                    contextField.isAccessible = true
                    contextField[frameBimapKit] = null
                } catch (ignore: Exception) {
                }
            }
            mBaiduPlayer!!.release()
        }
    }


    override fun finish() {
        super.finish()
        if (mBaiduPlayer != null && mBaiduPlayer!!.isPlaying && mBaiduPlayer!!.isAudioPlay()) {
            if (checkPermission(this)) {
                startReadNews()
                realFinish()
            } else {
                showPermissionAsk(this, object : OnPermissionResult {
                    override fun permissionResult(isOpen: Boolean) {
                        if (isOpen) {
                            startReadNews()
                        }
                        realFinish()
                    }
                })
            }
        } else {
            realFinish()
        }
    }

    override fun getStatusBarColor(): Int {
        return Color.BLACK
    }

    override fun getBarTextColorIsDefault(): Boolean {
        return false
    }

    override fun refreshStatusBarColor() {
        StatusBarUtil.setColorNoTranslucent(this, Color.BLACK)
        StatusBarUtil.setDarkMode(this)
    }

    override fun getLayoutResID(): Int {
        return R.layout.aappfactory_activity_videovod_detail
    }


    fun setVideoPlayerData() {
        mBaiduPlayer!!.bottomControl.setPendingPlayerChangeListener(object :
            PendingPlayerChangeListener {
            override fun onPendingPlayerStateChange() {
                color(null)
            }
        })
        mBaiduPlayer!!.addOnStateChangeListener(object : OnStateChangeListener {
            override fun onPlayerStateChanged(playerState: Int) {
                if (playerState == VideoView.STATE_PAUSED) {
                }
            }

            override fun onPlayStateChanged(playState: Int) {
                try {
                    if (playState == VideoView.STATE_PAUSED) {
                        stopPosition = mBaiduPlayer!!.currentPosition
                        getInstance().app_jhapp_content_detail_interact(
                            "停止播放视频",
                            if (isCompleted) "是" else "否",
                            ((stopPosition - startPosition) / 1000).toString(),
                            articleItem,
                            0,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            PlayerUtils.stringForTime(startPosition.toInt()),
                            null,
                            PlayerUtils.stringForTime(stopPosition.toInt())
                        )
                    } else if (playState == VideoView.STATE_PLAYBACK_COMPLETED) {
                        if (!isFinish) {
                            deleteHistoryPosition()
                        }
                        isCompleted = true
                        getInstance().app_jhapp_content_detail_interact(
                            "播完视频",
                            "是", ((videoDuration - startPosition) / 1000).toString(), articleItem
                        )
                    } else if (playState == VideoView.STATE_PLAYING) {
                        startPosition = mBaiduPlayer!!.currentPosition
                        videoDuration = mBaiduPlayer!!.duration
                        getInstance().app_jhapp_content_detail_interact(
                            "开始播放视频",
                            null,
                            null,
                            articleItem,
                            0,
                            null,
                            PlayerUtils.stringForTime(startPosition.toInt())
                        )
                    } else if (playState == VideoView.STATE_BUFFERED) {
//                        startPosition = mBaiduPlayer.getCurrentPosition();
                        dragAfterPosition = mBaiduPlayer!!.currentPosition
                        getInstance().app_jhapp_content_detail_interact(
                            if (isForwardComplate) "拖动视频进度条（快进）" else "拖动视频进度条（快退）",
                            null,
                            null,
                            articleItem,
                            0,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            PlayerUtils.stringForTime(dragBeforePosition.toInt()),
                            PlayerUtils.stringForTime(dragAfterPosition.toInt())
                        )
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })
        mBaiduPlayer!!.onPlayerActionListener = object : OnPlayerActionListener {
            override fun onProjectionScreen() {
                //投屏回调
                getInstance().app_jhapp_content_detail_interact(
                    "点击投屏",
                    null,
                    null,
                    articleItem
                )
            }

            override fun onSpeedChange(before: XVideoSpeed?, after: XVideoSpeed) {
                getInstance().app_jhapp_content_detail_interact(
                    "切换倍速",
                    null,
                    null,
                    articleItem,
                    0,
                    null,
                    null,
                    null,
                    null,
                    before!!.title,
                    after.title
                )
            }

            override fun onBitRateChange(before: XVideoBitRate?, after: XVideoBitRate) {
                getInstance().app_jhapp_content_detail_interact(
                    "切换码率",
                    null,
                    null,
                    articleItem,
                    0,
                    null,
                    null,
                    before!!.title,
                    after.title
                )
            }

            override fun onDamuSwitch(isOpen: Boolean) {
                if (isOpen) {
                } else {
                }
            }

            override fun onPlayerStateChanged(playerState: Int) {
                val isFullScreen = playerState == VideoView.PLAYER_FULL_SCREEN
                if (isFullScreen) {
                    getInstance().app_jhapp_content_detail_interact(
                        "最大化视频窗口",
                        null,
                        null,
                        articleItem
                    )
                }
            }

            override fun onSeekTo(isForward: Boolean) {
                dragBeforePosition = mBaiduPlayer!!.currentPosition
                isForwardComplate = isForward
            }
        }
//        mBaiduPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
//            @Override
//            public void onpause(int currentMediaIndex) {
//                super.onpause(currentMediaIndex);
//                if (pauseAd != null)
//                    mBaiduPlayer.showAdPausevertiseView(pauseAd);
//                ReportManager.getInstance().pause_play_video(articleItem.getVid(),articleItem.getType()+"",articleItem.getId()+"",articleItem.getTitle(),
//                        articleItem.getId()+"",articleItem.getTitle(),articleItem.getReferName(),articleItem.getAuthor(),articleItem.getAuthor(),currentMediaIndex+"");
//
//            }
//
//            @Override
//            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
//                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
////                DisplayCutoutManager dcm = new DisplayCutoutManager(VideoVodDetailActivity.this);
////
////
//                if (isFullScreen) {
//                    vodBottomContent.setVisibility(View.GONE);
//                    bottomBarLayout.setVisibility(View.GONE);
//                    ReportManager.getInstance().fullscreen_play_video(articleItem.getVid(),articleItem.getType()+"",articleItem.getId()+"",articleItem.getTitle(),
//                            articleItem.getId()+"",articleItem.getTitle(),articleItem.getReferName(),articleItem.getAuthor(),articleItem.getAuthor(),currentMediaIndex+"");
//                } else {
//                    vodBottomContent.setVisibility(View.VISIBLE);
//                    bottomBarLayout.setVisibility(View.VISIBLE);
//                }
////                    mTitileBar.setVisibility(View.GONE);
////                    findViewById(R.id.vodBottomContent).setVisibility(View.GONE);
////                    if (dcm.isCutoutScreen()) {//用于处理华为刘海屏不能全屏到问题
////                        mBaiduPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE |
////                                View.SYSTEM_UI_FLAG_FULLSCREEN |
////                                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
////                                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
////                    }
////                } else {
////                    findViewById(R.id.vodBottomContent).setVisibility(View.VISIBLE);
////                    mTitileBar.setVisibility(View.VISIBLE);
////                    if (dcm.isCutoutScreen()) {//刘海屏处理
////
////                        mBaiduPlayer.setSystemUiVisibility(0);
////                    }
////                }
//            }
//
//            @Override
//            public void oncomplete(int currentMediaIndex) {
//                super.oncomplete(currentMediaIndex);
//                seekTime = 0;
//                if (!isFinish)
//                    deleteHistoryPosition();
//            }
//
//            @Override
//            public void onstop(int currentMediaIndex) {
//                super.onstop(currentMediaIndex);
//                if (!isFinish)
//                    deleteHistoryPosition();
//            }
//
//            @Override
//            public void onPrepared(int currentMediaIndex) {
//                super.onPrepared(currentMediaIndex);
//                mBaiduPlayer.toggleFullScreenEnable(true);
//                ReportManager.getInstance().play_video(articleItem.getVid(),articleItem.getType()+"",articleItem.getId()+"",articleItem.getTitle(),
//                        articleItem.getId()+"",articleItem.getTitle(),articleItem.getReferName(),articleItem.getAuthor(),articleItem.getAuthor());
//                KillMusicUtils.stopAudioPlay(VideoVodDetailActivity.this);
//                try {
//                    String[] times = articleItem.getProp4().split(":");
//                    int hours, min, sec;
//                    hours = Integer.valueOf("" + times[0]);
//                    min = Integer.valueOf("" + times[1]);
//                    sec = Integer.valueOf("" + times[2]);
//                    int total = hours * 60 * 60;
//                    total += min * 60;
//                    total += sec;
//                    if (total > 0)
//                        mBaiduPlayer.setConfigDuration(total);
//                } catch (Exception e) {
//                    // TODO: handle exception
//                }
//                if (seekTime > 0) {
//                    mBaiduPlayer.post(() -> {
//                        if (seekTime >= mBaiduPlayer.getDuration())
//                            return;
//                        mBaiduPlayer.seek(seekTime);
//                        String seek_last_position_tips = getResources().getString(R.string.seek_last_position_tips);
//                        seek_last_position_tips += Tools.convertTimeFormat((int) seekTime);
//                        seekTime = 0;
//                        if (!isOutView)
//                            ToastUtil.show(VideoVodDetailActivity.this, seek_last_position_tips, Gravity.CENTER);
//                    });
//                } else {
//                    if (isOutView)
//                        stopShareBgPlayBug();
//                }
//            }
//
//            @Override
//            public void onSeekComplete(int currentMediaIndex) {
//                super.onSeekComplete(currentMediaIndex);
//                if (isOutView)
//                 stopShareBgPlayBug();
//                seekTime = 0;
//            }
//
//            @Override
//            public void onVideoComletionAd() {
//                super.onVideoComletionAd();
//            }
//        });
    }

//    protected final void stopShareBgPlayBug() {
//        mRootView.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (isOutView && mBaiduPlayer != null)
//                    mBaiduPlayer.pause();
//            }
//        }, 500);
//    }

    //    protected final void stopShareBgPlayBug() {
    //        mRootView.postDelayed(new Runnable() {
    //            @Override
    //            public void run() {
    //                if (isOutView && mBaiduPlayer != null)
    //                    mBaiduPlayer.pause();
    //            }
    //        }, 500);
    //    }
    protected fun deleteHistoryPosition() {
        clearHisSeek("" + articleItem.getId())
    }

    fun saveViewHistory() {
        if (mBaiduPlayer != null) {
            if (mBaiduPlayer!!.currentPlayState == VideoView.STATE_PLAYBACK_COMPLETED) {
                deleteHistoryPosition()
            } else if (mBaiduPlayer!!.currentPosition > 0 && mBaiduPlayer!!.currentPosition < mBaiduPlayer!!.duration) {
                addViewHistory(mBaiduPlayer!!.currentPosition)
            }
        }
    }

    protected fun addViewHistory(position: Long) {
        addHisSeek("" + articleItem.getId(), position)
    }

    var mp4Data: String? = null


    fun success(data: ArticleItemReciver) {
        if (data.state && data.articleItem != null) {
            articleItem = data.articleItem
            if (articleItem.isComment == "0") {
                isComment = articleItem.isComment
                orderView()
            }
            sendExposureEvent()
            refreshBottomStyle(data.articleItem, 1)
            UserRecommend.addItemKeyWord(articleItem, this)
            articleItem.mShowSwitch = showSwitch
            if (hadAdded) {
                fragment!!.articleItem = articleItem
            }
            if (TextUtils.isEmpty(articleItem.goodsID)) {
                initDetailFragment(data, true)
            } else {
                initDetailFragment(data, false)
            }

            setVideoContent(articleItem.video)
        } else {
        }
        if (!isAddIntegral) {
            isAddIntegral = true
            startAddIntegralCounter()
        }
    }

    var isAddIntegral = false

    private fun startAddIntegralCounter() {
        AddIntegralCounter.start(this, TimeoutCallback {
            if (articleItem == null) {
                return@TimeoutCallback
            }
            //                Addintegral.addintegral(VideoVodDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
        })

        //开启视频任务时
        if (openInteval) {
            AddIntegralCounter.start(this, TimeoutCallback {
                if (articleItem == null) {
                    return@TimeoutCallback
                }
                Addintegral.addintegral(
                    this@VideoNewsDetailActivity,
                    articleItem.getId(),
                    8,
                    if ("1" == articleItem.movie.isStudyContent) "1" else "0",
                    false,
                    articleItem
                )
            }, timeInteval, AddIntegralCounter.VideoTask)
        }
    }

    fun hiddBroccoliLayout() {
        if (rlayout_back != null) {
            rlayout_back.visibility = View.GONE
        }
        broccoliLayout!!.visibility = View.GONE
        closeStateView()
    }

    var lastPlayUrl: String? = ""

    private fun setVideoContent(videoStr: String) {
        if (articleItem != null) {
            mBaiduPlayer!!.setPoster(
                buildUrl(3, articleItem.logo),
                ContextCompat.getDrawable(this, R.drawable.cctv7_loading_img)
            )
        }
        try {
            val video = JSONObject(videoStr)
            val cdn = video.optString("cdnConfigEncrypt")
            val poster = video.optString("poster", "")
            //            if (TextUtils.isEmpty(poster)) {
//                mBaiduPlayer.setPoster(articleItem.getLogo(), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
//            } else {
//                mBaiduPlayer.setPoster(poster, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
//            }
            val tsAddress = VideoAddressGet.getAddress(video)
            if (tsAddress != null) mp4Data = tsAddress.toString()
            val videoItem = XVideoItem(
                articleItem.getTitle(),
                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key,
                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
            )
            var i = 0
            while (tsAddress != null && i < tsAddress.length()) {
                val line = tsAddress.optJSONObject(i)
                if (line.has("title")) {
                    val lineItem = XVideoBitRate()
                    //"https://video.mjh.pladaily.com.cn/0/b81ab1497ae1133dbc41e584912d77aa/2022/10/06/9754841582fd4fcb9e5ea1a43c190f79/9754841582fd4fcb9e5ea1a43c190f79_1080_hls_210852.m3u8"
                    lineItem.path = line.optString("url")
                    lineItem.title = line.optString("title")
                    lineItem.cdnEncypt = cdn
                    if (!TextUtils.isEmpty(lineItem.path)) {
                        videoItem.bitRates.add(lineItem)
                        lastPlayUrl = lineItem.path
                    }
                }
                i++
            }
            mBaiduPlayer!!.addVideoItemReverse(videoItem, "源码", true)
            if (DeviceUtils.isCus(this)) {
                mBaiduPlayer!!.setDolbySwitchViewState(true, null)
            }
            //视频详情类型 并且未缓存过
            if (articleItem.getType() == 5 && !XPlayerPreloadManager.getInstance(this).isPreloaded(
                    videoItem.bitRates[videoItem.bitRates.size - 1].path
                )
            ) {
                XPlayerPreloadManager.getInstance(this)
                    .addPreloadTask(videoItem.bitRates[videoItem.bitRates.size - 1].path)
            }
            if (videoItem.bitRates.size > 0) {
                setVideoPlayerData()
            } else {
                mBaiduPlayer!!.onExternalError()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "" + e.message)
            //            mBaiduPlayer.onExternalError();
        }
    }

    var hadAdded = false

    protected fun initDetailFragment(data: ArticleItemReciver, appfacBuy: Boolean) {
        if (hadAdded) return
        val args = Bundle()
        args.putParcelable("data", data.articleItem)
        args.putParcelable("catalog", catalogItem)
        args.putBoolean("appfacBuy", appfacBuy)
        args.putParcelableArrayList("components", data.components)
        fragment!!.arguments = args
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.vodBottomContent, fragment!!)
        transaction.show(fragment!!)
        transaction.commitAllowingStateLoss()
        hadAdded = true
        readStatus()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        if (requestCode == MemberActivity.REQUEST_CODE && intent != null && intent.getBooleanExtra(
                MemberActivity.REQUEST_KEY,
                false
            )
        ) {
        }
    }

    var readStatusInvoker: ReadStatusInvoker? = null

    var isSendRead = false

    fun readStatus() {
        if (!isSendRead) {
            readStatusInvoker = ReadStatusInvoker(object : DataInvokeCallBack<ReadDataReciver?> {

                override fun success(data: ReadDataReciver?) {
                    AnalysisUtils.readsAnalysis(
                        applicationContext,
                        articleItem,
                        data?.virtualIncrement!!
                    )

                    runOnUiThread { fragment!!.setVideoReades(data?.reads?.toInt()!!) }
                }

                override fun fault(data: Any) {
                    AnalysisUtils.readsAnalysis(
                        applicationContext,
                        articleItem,
                        AnalysisUtils.DefaultVirtualIncrement
                    )
                }
            })
            readStatusInvoker!!.readStatistics(articleItem.getId().toString() + "", 1)
            isSendRead = true
        }
    }

    override fun onStart() {
        super.onStart()
        launchTimeLong = System.currentTimeMillis()
        if (articleItem != null) {
            val info = UserInfo.getUserInfo(this)
            AcquisitionManager.getInstance().readEnter(
                info,
                "" + articleItem.getId(),
                DomainUtil.getDomain(articleItem.getUrl()),
                articleItem.getUrl(),
                articleItem.getTitle(),
                articleItem.content
            )
        }
    }

    override fun onStop() {
        super.onStop()
        if (articleItem != null) {
            val info = UserInfo.getUserInfo(this)
            AcquisitionManager.getInstance().readExit(
                info,
                "" + articleItem.getId(),
                DomainUtil.getDomain(articleItem.getUrl()),
                articleItem.getUrl(),
                articleItem.getTitle(),
                articleItem.content
            )
        }
    }

    override fun isShowNetWorDialog(): Boolean {
        return false
    }

    override fun onResume() {
        super.onResume()
        if (isGoOtherPage) {
            if (!isPlayBeforePause) mBaiduPlayer!!.resume()
            isGoOtherPage = false
        }
    }

    override fun noNetwork() {
//        showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
//        if (rlayout_back != null) {
//            rlayout_back.setVisibility(View.VISIBLE);
//        }
    }

    override fun onDestroy() {
        super.onDestroy()
        CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,(stopPosition - startPosition) / 1000)
        getInstance().app_jhapp_content_detail_interact(
            "退出浏览",
            if (isCompleted) "是" else "否", ((stopPosition - startPosition) / 1000).toString(),
            articleItem,
            (System.currentTimeMillis() - launchTimeLong) / 1000,
            null,
            null,
            null,
            null,
            null,
            null,
            PlayerUtils.stringForTime(stopPosition.toInt())
        )
    }


    fun getVideoDetail() {
        val map: MutableMap<String?, String?> = HashMap()
        map["client"] = "android"
        var catalogItem = intent.getParcelableExtra<CatalogItem>("catalog")
        if (catalogItem == null) {
            catalogItem = CatalogItem()
            var nid = intent.getStringExtra("navigate_id")
            if (nid == null) {
                nid = ""
            }
            catalogItem.catid = nid
        }
        val navigate_id = if (catalogItem != null) catalogItem.catid else ""
        if (!TextUtils.isEmpty(navigate_id)) {
            map["navigate_id"] = "navigate_id"
        }
        map["no_content"] = "1"
        DataInvokeUtil.ziMeiTiApi
            .getArticleById("" + articleItem.getId(), map)
            .map { jsonObjectResponse ->
                val articleItemReciver = ArticleItemReciver()
                articleItemReciver.readFromJson(jsonObjectResponse.body())
                articleItemReciver
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleItemReciver> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(articleItemReciver: ArticleItemReciver) {
                    success(articleItemReciver)
                }

                override fun onError(e: Throwable) {
                }

                override fun onComplete() {}
            })
    }
}